package cn.crce.cloud9.comp;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * @author OnCloud9
 * @description
 * @project NRCE-TEST
 * @date 2022年09月13日 下午 08:48
 */
public class Case20 extends JFrame {
    public Case20() {
        super("打印无符号整数位");
        Container c = getContentPane();
        c.setLayout(new FlowLayout());
        c.add(new JLabel("请输入整数: "));
        final JTextField output = new JTextField(33);
        JTextField input = new JTextField(10);
        input.addActionListener(
                new ActionListener() {
                    //*********Found********
                    public void actionPerformed(ActionEvent e) {
                        int val = Integer.parseInt(
                                e.getActionCommand());
                        //*********Found********
                        output.setText(getBits(val));
                    }
                }
        );
        c.add(input);
        c.add(new JLabel("该数的二进制位表示是"));
        output.setEditable(false);
        //*********Found********
        c.add(output);
        setSize(720, 70);
        setVisible(true);
    }

    private String getBits(int value) {
        int displayMask = 1 << 31;
        StringBuffer buf = new StringBuffer(35);
        for (int c = 1; c <= 32; c++) {
            buf.append(
                    (value & displayMask) == 0 ? '0' : '1');
            value <<= 1;
            if (c % 8 == 0)
                buf.append(' ');
        }
        return buf.toString();
    }

    public static void main(String args[]) {
        Case20 app = new Case20();
        app.addWindowListener(
                new WindowAdapter() {
                    //*********Found********
                    public void windowClosing(WindowEvent e) {
                        System.exit(0);
                    }
                }
        );
    }
}
